#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>

int main(int argc, char *argv[])
{
    int tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcp_fd < 0)
    {
        perror("socket fail");
        return -1;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(struct sockaddr_in));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(50000);
    inet_pton(AF_INET, "0.0.0.0", &server_addr.sin_addr);

    int ret = bind(tcp_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    listen(tcp_fd, 1);

    printf("It is waitting\n");
    
    struct sockaddr_in con_addr;
    socklen_t len = sizeof(con_addr);
    int con_fd = accept(tcp_fd,(struct sockaddr*)&con_addr,&len);
    
    printf("con id = %s\n",inet_ntoa(con_addr.sin_addr));
    printf("con port = %hu\n",ntohs(con_addr.sin_port));

    char buf[1024] = {0};

    while(1)
    {
      memset(buf,0,1024);
      read(con_fd,buf,1024);
      printf("read is %s\n",buf);
      if(!strcmp("bye",buf))
        break;
    }

    close(con_fd);
    close(tcp_fd);
    return 0;
}
